package com.wing.order.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.exception.BusinessException;
import com.wing.web.db.config.util.DynamicDataSource;
import com.wing.order.dao.CabInventoryProductDao;
import com.wing.order.model.entity.CabInventoryProduct;
import com.wing.order.model.entity.CabInventoryProductRecord;
import com.wing.order.model.request.CabInventoryProductForm;
import com.wing.order.model.response.CabInventoryProductVO;
import com.wing.platform.feign.PlatformClient;
import com.wing.product.model.entity.ProductDetail;
import com.wing.product.model.entity.ProductPack;
import com.wing.product.model.entity.ProductUnitInfo;
import com.wing.product.service.ProductDetailService;
import com.wing.product.service.ProductPackService;
import com.wing.product.service.ProductUnitService;
import com.wing.system.model.response.EnterpricceIdVO;
import com.wing.system.service.EnterpricceIdService;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 产品库存-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class CabInventoryProductServiceImpl extends ServiceImpl<CabInventoryProductDao, CabInventoryProduct> implements CabInventoryProductService {

    @Autowired
    private CabInventoryProductDao cabInventoryProductDao;

    @Autowired
    private EnterpricceIdService enterpricceIdService;

    @Autowired
    private PlatformClient platformClient;

    @Autowired
    private CabInventoryProductRecordService cabInventoryProductRecordService;

    @Autowired
    private ProductPackService productPackService;

    @Autowired
    private ProductDetailService productDetailService;

    @Autowired
    private ProductUnitService productUnitService;

    @Override
    public int add(CabInventoryProductForm cabInventoryProductForm) {

        //校验

        CabInventoryProduct cabInventoryProduct =new CabInventoryProduct();
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(CabInventoryProduct.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(cabInventoryProductForm, cabInventoryProduct, copyOptions);

        return baseMapper.insert(cabInventoryProduct);
    }

    @Override
    public List<CabInventoryProductVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<CabInventoryProductVO> pageList4app(Page page, Map<String, Object> params) {
        List<CabInventoryProductVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public CabInventoryProductVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    public CabInventoryProduct getInventoryProductVOBySkuCode(String skuCode,Long warehouseId,Integer sourceType) {
        return cabInventoryProductDao.getCabInventoryProductVOBySkuCode(skuCode,warehouseId,sourceType);
    }

    @Override
    public List<CabInventoryProduct> getInventoryProductByType() {
        QueryWrapper<CabInventoryProduct> wrapper = new QueryWrapper<>();
        wrapper.eq("type",0);
        List<CabInventoryProduct> list = cabInventoryProductDao.selectList(wrapper);
        return list;
    }

    @Override
    public List<Object> getCabInventoryProductBySkuCodeAndType(String skuCode) {
        // 获取当前企业
        EnterpricceIdVO enterpricceIdVO = enterpricceIdService.getEnterpricceIdVO();
        List<Object> list = Lists.newArrayList();
        // 查询本地库存
        String databaseUser = DynamicDataSource.USER_PREFIX;
        if(StringUtils.isNotBlank(DynamicDataSource.name.get())){
            databaseUser = databaseUser + "-" + DynamicDataSource.name.get();
        }
        List<CabInventoryProductVO> inventoryProductVOList = cabInventoryProductDao.getCabInventoryProductBySkuCodeAndType(skuCode, databaseUser);
        list.addAll(inventoryProductVOList);
        return list;
    }

    @Override
    @Transactional
    public int saveCabInventoryProduct(CabInventoryProductForm cabInventoryProductForm) {
        int result = 0;
        /**
        Integer quantityReal=0;
        int quantityPack = 0;
        int quantityPackUnit = 0;
        CabInventoryProduct cabInventoryProductVo = baseMapper.getCabInventoryProductVOBySkuCode(cabInventoryProductForm.getSkuCode(), cabInventoryProductForm.getWarehouseId(), 0);

        if(cabInventoryProductForm.getPackId()!=null){
            ProductPack productPack = productPackService.getById(cabInventoryProductForm.getPackId());
            if(productPack!=null){
                quantityPack = cabInventoryProductForm.getQuantity()*productPack.getBaseRate();
                quantityPackUnit = productPack.getBaseRate();
            }
        }*/
        Integer quantityPackUnit=cabInventoryProductForm.getQuantityPackUnit();
        Integer quantityPack=quantityPackUnit*cabInventoryProductForm.getQuantity();
        List<CabInventoryProduct> list=baseMapper.selectList(new QueryWrapper<CabInventoryProduct>().eq("sku_code",cabInventoryProductForm.getSkuCode()).eq("warehouse_id",cabInventoryProductForm.getWarehouseId()).eq("quantity_pack_unit",cabInventoryProductForm.getQuantityPackUnit()).eq("source_type",0));
        // 添加记录
        CabInventoryProductRecord cabInventoryProductRecord = new CabInventoryProductRecord();
        BeanUtil.copyProperties(cabInventoryProductForm,cabInventoryProductRecord);
        if(list.size()>0){

            CabInventoryProduct cabInventoryProductVo=list.get(0);
//            quantityReal=cabInventoryProductVo.getQuantityReal();
            Integer quantityCurrent = cabInventoryProductVo.getQuantity();
            Integer quantityPackCurrent=cabInventoryProductVo.getQuantityPack();
            if(cabInventoryProductForm.getInOutType().equals("in")){
                cabInventoryProductVo.setQuantity(quantityCurrent+cabInventoryProductForm.getQuantity());
//              cabInventoryProductVo.setQuantityReal(cabInventoryProductVo.getQuantityReal()+cabInventoryProductForm.getQuantity());
                cabInventoryProductVo.setQuantityPack(quantityPackCurrent+quantityPack);
//              cabInventoryProductVo.setQuantityPackUnit(quantityPackUnit);
                cabInventoryProductRecord.setType(CabInventoryProductRecord.Type.in);
            }else{
                if(quantityCurrent-cabInventoryProductForm.getQuantity() < 0){
                    throw new BusinessException(500, "库存不足");
                }
                if(quantityPackCurrent-quantityPack < 0){
                    throw new BusinessException(500, "包装数库存不足");
                }
                cabInventoryProductVo.setQuantity(quantityCurrent-cabInventoryProductForm.getQuantity());
                cabInventoryProductVo.setQuantityPack(quantityPackCurrent-quantityPack);
                cabInventoryProductRecord.setType(CabInventoryProductRecord.Type.out);
            }
            result = baseMapper.updateById(cabInventoryProductVo);
            cabInventoryProductRecord.setQuantityCurrent(quantityCurrent);
            cabInventoryProductRecord.setQuantityAfter(cabInventoryProductVo.getQuantity());
            cabInventoryProductRecord.setQuantityPackCurrent(quantityPackCurrent);
            cabInventoryProductRecord.setQuantityPackAfter(cabInventoryProductVo.getQuantityPack());
        }else {
            if(cabInventoryProductForm.getInOutType().equals("in")){
                CabInventoryProduct cabInventoryProduct =new CabInventoryProduct();
                CopyOptions copyOptions = CopyOptions.create()
                        .setEditable(CabInventoryProduct.class)
                        .setIgnoreError(true)
                        .setIgnoreNullValue(true);
                BeanUtil.copyProperties(cabInventoryProductForm, cabInventoryProduct, copyOptions);
                cabInventoryProduct.setSkuType(1);
                cabInventoryProduct.setEnterpriseCode(JwtUtils.getEnterpriseCode());
//            cabInventoryProduct.setQuantityReal(cabInventoryProductForm.getQuantity());
                cabInventoryProduct.setQuantityPack(quantityPack);
                cabInventoryProduct.setQuantityPackUnit(quantityPackUnit);

                result = baseMapper.insert(cabInventoryProduct);
                cabInventoryProductRecord.setQuantityCurrent(0);
                cabInventoryProductRecord.setQuantityAfter(cabInventoryProduct.getQuantity());
                cabInventoryProductRecord.setQuantityPackCurrent(0);
                cabInventoryProductRecord.setQuantityPackAfter(quantityPack);
                cabInventoryProductRecord.setType(CabInventoryProductRecord.Type.in);
            }else{
                throw new BusinessException(500, "无库存数据");
            }
        }
        cabInventoryProductRecord.setQuantityPack(quantityPack);
        cabInventoryProductRecord.setSkuCode(cabInventoryProductForm.getSkuCode());
        cabInventoryProductRecord.setQuantity(cabInventoryProductForm.getQuantity());
        cabInventoryProductRecord.setWarehouseId(cabInventoryProductForm.getWarehouseId());
        cabInventoryProductRecord.setEnterpriseCode(JwtUtils.getEnterpriseCode());
        cabInventoryProductRecord.setCreatorName(JwtUtils.getLoginUsername());
        cabInventoryProductRecord.setWarehouseInventoryTypeId(cabInventoryProductForm.getWarehouseInventoryTypeId());
        cabInventoryProductRecordService.save(cabInventoryProductRecord);
        /**
        CabInventoryProductRecord cabInventoryProductRecordTarget=new CabInventoryProductRecord();
        BeanUtil.copyProperties(cabInventoryProductRecord,cabInventoryProductRecordTarget);
        cabInventoryProductRecordTarget.setId(null);
        cabInventoryProductRecordTarget.setQuantityAfter(cabInventoryProductForm.getQuantity());
        if(cabInventoryProductVo!=null){
            cabInventoryProductRecordTarget.setQuantityCurrent(quantityReal);
            cabInventoryProductRecordTarget.setQuantityAfter(cabInventoryProductVo.getQuantityReal());
        }else{
            cabInventoryProductRecordTarget.setQuantityCurrent(0);
            cabInventoryProductRecordTarget.setQuantityAfter(cabInventoryProductForm.getQuantity());
        }
        cabInventoryProductRecordTarget.setType(CabInventoryProductRecord.Type.in4Real);
        cabInventoryProductRecordService.save(cabInventoryProductRecordTarget);
         */

        // 修改物料
        ProductDetail productDetail = productDetailService.getOne(new QueryWrapper<ProductDetail>().eq("sku_code", cabInventoryProductForm.getSkuCode()));
        productDetailService.updateById(productDetail);
        return result;
    }
}
